<?php
class Picture {

	public static function makeThumb($pathToPic, $wideSide) {
		$conf = Fcf_Configurator::getInstance();
		$conf->readConfig(CONFIG_DIR . '/fcfMain.xml');
		
		$thumbDir = $conf->getString('picture/news/upldirthumb');
		$imgInfo = self::_getImgInfo(BASE_DIR . $pathToPic);
		$imgType = $imgInfo['mime'];
		switch($imgType) {
			case 'image/jpeg':
				$thImg = imagecreatefromjpeg(BASE_DIR . $pathToPic);
				$imgName = basename($pathToPic, '.jpg');
			break;
			case 'image/png':
				$thImg = imagecreatefrompng(BASE_DIR . $pathToPic);
				$imgName = basename($pathToPic . '.png');
		}
		$width = imagesx($thImg);
		$height = imagesy($thImg);
		
		if($width > $height) {
			$prop = self::_calcProportion($width, $height, $wideSide);
			$new_width = $prop['wide'];
			$new_height = $prop['small'];
		}
		else {
			$prop = self::_calcProportion($height, $width, $wideSide);
			$new_width = $prop['small'];
			$new_height = $prop['wide'];
		}
		
		$newImg = imagecreatetruecolor($new_width, $new_height);
		imagecopyresampled($newImg, $thImg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		$thumbName = $imgName . '_thmb.png';
		$thumbPath = $thumbDir . $thumbName;
		imagejpeg($newImg, BASE_DIR . $thumbPath, 100);
		return $thumbPath;
	}
	
	public static function resize($picPath, $newWidth, $newHeight) {
		$imgInfo = self::_getImgInfo(BASE_DIR . '/' . $picPath);
		$imgType = $imgInfo['mime'];
		switch($imgType) {
			case 'image/jpeg':
				$thImg = imagecreatefromjpeg(BASE_DIR . '/' . $picPath);
				$imgName = basename($picPath, '.jpg');
			break;
			case 'image/png':
				$thImg = imagecreatefrompng(BASE_DIR . '/' . $picPath);
				$imgName = basename($picPath . '.png');
			break;
		}
		$width = imagesx($thImg);
		$height = imagesy($thImg);
		
		$newImg = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($newImg, $thImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

		imagejpeg($newImg, BASE_DIR . '/' . $picPath, 100);
		return $picPath;
	}
	
	protected static function _calcProportion($imgWide, $imgSmall, $newWideSize) {
		$proportion = array();
		$propPercents = ceil(($imgSmall / $imgWide) * 100);
		$proportion['wide'] = $newWideSize;
		$proportion['small'] = ceil(($newWideSize / 100 ) * $propPercents);
		return $proportion;
	}
	
	protected static function _getImgInfo($img) {
		$imgInfo = getimagesize($img);
		return $imgInfo;
	}
	
	protected function _addWaterMarkText($wmText) {
		
	}
	
	public function getImgSrc() {
		
	}
}